<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>社区发布</title>
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel="stylesheet" href="${pageContext.request.contextPath}/plugins/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/AdminLTE.min.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/plugins/bootstrap-table/css/bootstrap-table.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/plugins/bootstrap_fileupload/css/fileinput.min.css"/>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/sweet-alert.css">
</head>
<style>
</style>
<body style="padding-bottom: 90px; background-color: #ECF0F5;">
	<section class="content" style="margin: 15px; background-color: white;">
		<div class="row">
			<div class="col-sm-12">
				<table id="table">
					<thead style="background-color: #00C0EF">
						<tr style="background-color: #00C0EF">
							<th class="text-center" data-field=""></th>
							<th class="text-center" data-field="noticeTitle">公告标题</th>
							<th class="text-center" data-field="noticeSource">来源</th>
							<th class="text-center" data-field="noticeTime">发布时间</th>
							<th class="text-center" data-field="noticePeople">操作员</th>
							<th class="text-center" data-field="noticeType">公告类型</th>
							<th class="text-center" data-field="noticeState">发布状态</th>
							<th class="text-center" data-field="id">操作</th>
						</tr>
					</thead>
				</table>
			</div>
		</div>
	</section>
	<!-- Large modal -->
	<div id="modal" class="modal fade bs-example-modal-lg" role="dialog">
		<div class="modal-dialog modal-lg" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close">
						<span aria-hidden="true">&times;</span>
					</button>
					<h4 class="modal-title">编辑窗口</h4>
				</div>
				<div class="modal-body">
					<div class="input-group">
						<span class="input-group-addon">标题</span> <input type="text" class="form-control" placeholder="必填" id="title">
					</div>
					<br />
					<div class="input-group">
                        <label for="activity_title" class="control-label">标题图片:</label>
						<button id="imgBtn" class="btn btn-primary glyphicon glyphicon-plus" onclick="imgFile.click();">上传图片</button>
						<img id="image" class="cover-radius" src="${pageContext.request.contextPath}/img/upload.jpg" width="150px;" style="cursor: pointer;" onclick="imgFile.click();" /> 
						<input type="file" class="form-control" style="display: none;" name="imgFile" id="imgFile" onchange="fileChange()"> 
						<small class="help-block cover-tips" style="color: #dd4b39; display: none;">请上传照片</small>
					</div>
					<br />
					<div class="input-group">
						<span class="input-group-addon">来源</span> <input type="text" class="form-control" placeholder="必填" id="source">
					</div>
					<br />
					<div class="input-group">
						<span class="input-group-addon">操作员</span> <input type="text" class="form-control" value="${sessionScope.userAccount}" id="people" disabled="disabled" >
					</div>
					<br />
					<div class="input-group">
						<span class="input-group-addon">公告类型</span> 
						<select id="type" class="form-control">
							<option value="">请选择...</option>
							<option value="1">社区速报</option>
							<option value="2">便民信息</option>
							<option value="3">活动通知</option>
							<option value="4">物业通知</option>
							<option value="5">系统通知</option>
						</select>
					</div>
					<br /> <br style="display: none;" id="jj2" />
					<div class="input-group">
						<span class="input-group-addon">内容</span>
						<textarea style="width: 100%; height: 500px;" class="form-control" rows="30" id="column1_textarea" name="kindEditor_content"></textarea>
					</div>
				</div>
				<div class="modal-footer">
					<button id="submitBtn" type="button" class="btn btn-primary" onclick="submitNotice();">保存</button>
					<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
				</div>
			</div>
		</div>
	</div>
</body>
<script src="${pageContext.request.contextPath}/plugins/jQuery/jquery-2.2.3.min.js"></script>
<script src="${pageContext.request.contextPath}/plugins/bootstrap/js/bootstrap.min.js"></script>
<script src="${pageContext.request.contextPath}/plugins/bootstrap-table/js/bootstrap-table.js"></script>
<script src="${pageContext.request.contextPath}/plugins/bootstrap-table/js/bootstrap-table-zh-CN.js"></script>
<script src="${pageContext.request.contextPath}/plugins/bootstrap-table/js/bootstrap-table-export.js"></script>
<script src="${pageContext.request.contextPath}/plugins/bootstrap-table/js/tableExport.js"></script>
<script src="${pageContext.request.contextPath}/plugins/bootstrap-table/js/bootstrap-table-toolbar.js"></script>
<script src="${pageContext.request.contextPath}/plugins/bootstrap-table/js/bootstrap-table-filter-control.js"></script>
<!-- kindeditor 编辑器 -->
<script charset="utf-8" src="${pageContext.request.contextPath}/kindeditor-4.1.10/kindeditor.js"></script>
<script charset="utf-8" src="${pageContext.request.contextPath}/kindeditor-4.1.10/lang/zh_CN.js"></script>

<%-- <script charset="utf-8" src="${pageContext.request.contextPath}/plugins/bootstrap_fileupload/js/fileinput.min.js"></script>
<script charset="utf-8" src="${pageContext.request.contextPath}/plugins/bootstrap_fileupload/js/locales/zh.js"></script> --%>
<!-- layer -->
<script src="${pageContext.request.contextPath}/plugins/layer/2.4/layer.js"></script>
<script src="${pageContext.request.contextPath}/js/sweet-alert.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/ajaxfileupload.js"></script>
<script src="${pageContext.request.contextPath}/js/date.js"></script>
<script>

	var noticeId = "";
	var nID="";
	var isChecked = true;
	var editor;
	var imgUrl="";
	
	var options={
			items : [ 'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste', 'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter',
						'justifyright', 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript', 'superscript', 'clearhtml', 'quickformat', 'selectall', '|',
						'fullscreen', '/', 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|',
						'image', 'multiimage', 'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak', 'anchor', 'link', 'unlink', '|', 'about' ], //配置kindeditor编辑器的工具栏菜单项
				cssPath : 'kindeditor-4.1.10/plugins/code/prettify.css',
				allowFileManager : true,
				uploadJson : '${pageContext.request.contextPath}/upload_img.do', //上传
				extraFileUploadParams : {
					mienId : ''
	        	},
				filterMode : true, //是否启用过滤模式(编辑文本框中是否可以出现控件显示)
				htmlTags : {
					span : [ '.color', '.background-color', '.font-size', '.font-family', '.background', '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.line-height' ],
					font : [ 'id', 'class', 'color', 'size', 'face', '.background-color' ],
					a : [ 'id', 'class', 'href', 'target', 'name' ],
					embed : [ 'id', 'class', 'src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess' ],
					img : [ 'id', 'class', 'src', 'width', 'height', 'border', 'alt', 'title', 'align', '.width', '.height', '.border' ],
					'p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6' : [ 'id', 'class', 'align', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.background', '.font-weight',
							'.font-style', '.text-decoration', '.vertical-align', '.text-indent', '.margin-left' ],
					pre : [ 'id', 'class' ],
					hr : [ 'id', 'class', '.page-break-after' ],
					'br,tbody,tr,strong,b,sub,sup,em,i,u,strike,s,del' : [ 'id', 'class' ],
					iframe : [ 'id', 'class', 'src', 'frameborder', 'width', 'height', '.width', '.height' ]
				},
				allowFileManager : true,
				allowUpload : true, //允许上传图片
				imageUploadJson : '/saveImg', //服务端上传图片处理URI
				resizeType : 0,//使其不可以拖动 
				afterCreate : function() {
					/* var self = this;
					K.ctrl(document, 13, function() {
						self.sync();
					});
					K.ctrl(self.edit.doc, 13, function() {
						self.sync();
					}); */
				},
				afterBlur : function() {
					this.sync();
				}
			}
	
	KindEditor.ready(function(K) {
		editor = K.create('textarea[name="kindEditor_content"]', options);
	});
	
	
	var table_dataset = [ {
		field : 'id',
		checkbox : true,
	}, {
		field : 'noticeTitle',
		align : 'center',
	}, {
		field : 'noticeSource',
		align : 'center',
	}, {
		field : 'noticeTime',
		align : 'center',
		formatter : function timeFormatter(value, row, index) {
			return (new Date(row.noticeTime)).Format("yyyy-MM-dd hh:mm:ss");
		}
	}, {
		field : 'noticePeople',
		align : 'center',
	}, {
		field : 'noticeType',
		align : 'center',
		formatter : typeFormatter,
	}, {
		field : 'noticeState',
		width : 50,
		align : 'center',
		formatter : actionNoticeState,
	},{
		align : 'center',
		width : 200,
		formatter : actionFormatter,
	} ];
	$('#table').bootstrapTable({
		url : "${pageContext.request.contextPath}/notice/selectNoticePage",
		idField : "id",
		columns : table_dataset,
		striped : true, //是否显示行间隔色
		pagination : true, //是否显示分页
		pageSize : 10, //每页的记录行数
		pageList : [ 10, 25, 50, 100 ], //可供选择的每页的行数
		search : false, //是否显示搜索
		showRefresh : true,
		sidePagination : "server", //表示服务端请求  
		queryParamsType : "limit",
		queryParams : function queryParams(params) { //设置查询参数  
			var param = {
				offset : params.offset,
				limit : params.limit,
				kod	  : $("#kod").val(),
				kodType : $("#kodType").val()
			};
			return param;
		},
		toolbar : "<button style='float:left;' class='btn btn-primary glyphicon glyphicon-plus' onclick='showModal(\"" + '' + "\");'>新增公告</button>"
		+"<div  style='width:250px;float:left;margin-top:2px;margin-left:20px;'>"
		+"<select id='kodType' name='stateType' class='form-control' onchange='Querry()'>"
		+"<option value=''>全部</option>"
		+"<option value='1'>社区速报</option>"
		+"<option value='2'>便民信息</option>"
		+"<option value='3'>活动通知</option>"
		+"<option value='4'>物业通知</option>"
		+"<option value='5'>系统通知</option>"
		+"</select></div>"
		+"<div class='input-group' style='width:250px;float:right;margin-top:2px;margin-left:20px;'><input type='text' class='form-control' placeholder='请输入公告标题' id='kod' name='kod'>"
		+ "<span class='input-group-btn'><button class='btn btn-default' type='button' onclick='Querry(\"" + '' + "\");'>查询</button></span></div>",
		icons : {
			paginationSwitchDown : 'glyphicon-collapse-down icon-chevron-down',
			paginationSwitchUp : 'glyphicon-collapse-up icon-chevron-up',
			refresh : 'glyphicon-refresh icon-refresh',
			toggle : 'glyphicon-list-alt icon-list-alt',
			columns : 'glyphicon-th icon-th',
			detailOpen : 'glyphicon-plus icon-plus',
			detailClose : 'glyphicon-minus icon-minus',
			"export" : 'glyphicon-export icon-share'
		},
		showExport : true,
		exportDataType : 'basic',
		exportTypes : [ 'json', 'xml', 'csv', 'txt', 'sql', 'excel' ]
	});
	
	function actionFormatter(value, row, index) {
		//console.log(row);
		return [ "<button class='btn btn-primary btn-xs glyphicon glyphicon-pencil' onclick='showModal(\"" + row.noticeId + "\");'>编辑</button>",
				"&nbsp;<button class='btn btn-danger btn-xs glyphicon glyphicon-trash' onclick='delNotice(\"" + row.noticeId+"\")'>删除</button>",
				].join('');
	}
	
	function actionNoticeState(value, row, index){
		//console.log(row.noticeState);
		if(row.noticeState==0){
			return [ "<button class='btn btn-danger btn-xs glyphicon ' onclick='releaseNotice(\"" + row.noticeId+ "\",\""+row.noticeState+"\")'>未发布</button>",].join('');
		}else{
			return [ "<button class='btn btn-success btn-xs glyphicon ' onclick='releaseNotice(\"" + row.noticeId+"\",\""+row.noticeState+"\")'>已发布</button>",].join('');
		}
		
	}
	
	function typeFormatter(value, row, index){
		if(row.noticeType==1){
			return "社区速报";
		}else if(row.noticeType==2){
			return "便民信息";
		}else if(row.noticeType==3){
			return "活动通知";
		}else if(row.noticeType==4){
			return "物业通知";
		}else if(row.noticeType==5){
			return "系统通知";
		}
	}

	function showModal(id) {
		if (id == "") {
			noticeId = '';
			nID=guid();
			imgUrl = "";
			$("#imgBtn").show();
			$('#image').attr('src', '');
			$('#title').val('');
			$('#source').val('');
			$("#people").val("${sessionScope.userAccount}");
			$('#type').val('');
			editor.html('');
			$('#modal').modal({
				backdrop : 'static',
				keyboard : false
			});
		} else {
			noticeId = id;
			nID=id;
			$.ajax({
				url : "${pageContext.request.contextPath}/notice/selectById",
				type : "get",
				data : {
					noticeId : noticeId
				},
				dataType : "json",
				success : function(data) {
					var notice=data.notice;
					console.log(notice);
					editor.html('');
					$('#title').val(notice.noticeTitle);
					$('#source').val(notice.noticeSource);
					$("#people").val(notice.noticePeople);
					$('#type').val(notice.noticeType);
					editor.insertHtml(notice.noticeContent);
					if (notice.noticeImg != null && notice.noticeImg != "") {
						imgUrl = notice.noticeImg;
						$('#image').attr('src', '${pageContext.request.contextPath}/' + notice.noticeImg);
						$("#imgBtn").hide();
						$('#image').show();
					} else {
						$("#imgBtn").show();
					}
					$('#modal').modal({
						backdrop : 'static',
						keyboard : false
					});
				},
				error : function() {
					layer.msg('系统异常!', {
						icon : 2,
						time : 800
					});
				}
			});
		}
	}


	function submitNotice() {
		$("#submitBtn").button('loading');
		var noticeTitle = $('#title').val();
		var noticeSource = $('#source').val();
		var noticePeople = $("#people").val();
		var noticeType = $('#type').val();
		var noticeContent = $('#column1_textarea').val();
		
		var url=noticeId==='' ? "${pageContext.request.contextPath}/notice/insertNotice":"${pageContext.request.contextPath}/notice/updateNotice";
		if(noticeTitle==""){
			layer.msg('请填写标题!', {
				icon : 2,
				time : 800
			});
			$("#submitBtn").button('reset');
			return;
		}
		
		if(noticeSource==""){
			layer.msg('请填写来源!', {
				icon : 2,
				time : 800
			});
			$("#submitBtn").button('reset');
			return;
		}
		
		if(noticeType==""){
			layer.msg('请选择类型!', {
				icon : 2,
				time : 800
			});
			$("#submitBtn").button('reset');
			return;
		}
		
		if(noticeType=="1"){
			if(imgUrl==""){
				layer.msg('请添加图片!', {
					icon : 2,
					time : 800
				});
				$("#submitBtn").button('reset');
				return;
			}
		}
		
		if(noticeContent==""){
			layer.msg('请填写内容!', {
				icon : 2,
				time : 800
			});
			$("#submitBtn").button('reset');
			return;
		}
		if(editor.isEmpty()){
			layer.msg('请填写内容!', {
				icon : 2,
				time : 800
			});
			$("#submitBtn").button('reset');
			return;
		}
			
			//console.log(imgUrl);
			$.ajax({
     			url : url,
     			type : "post",
     			dataType : "json",
     			data : {
     				noticeId:nID,
     				noticeTitle : noticeTitle,
     				noticeSource : noticeSource,
     				noticePeople : noticePeople,
     				noticeType : noticeType,
     				noticeContent : noticeContent,
     				noticeImg:imgUrl
     			},
     			success : function(data) {
     				var result = data['result'];
     				if (result =="1") {
     					layer.msg('操作成功!', {
     						icon : 1,
     						time : 800
     					});
     					setTimeout(function() {
     						$("#table").bootstrapTable('refresh');
     						$("#modal").modal("hide");
     					}, 1000);
     				} else {
     					layer.msg('操作失败!', {
     						icon : 2,
     						time : 800
     					});
     				}
     				$("#submitBtn").button('reset');
     			},
     			error : function() {
     				layer.msg('系统繁忙，请稍后再试!', {
     					icon : 2,
     					time : 800
     				});
     				$("#submitBtn").button('reset');
     			}
     		});
		//console.log(imgUrl);
		
	}

	function delNotice(id) {
		layer.confirm("是否要删除此公告？", function(index) {
			$.ajax({
				url : "${pageContext.request.contextPath}/notice/deleteNotice",
				type : "post",
				data : {
					noticeId : id
				},
				dataType : "json",
				success : function(data) {
					if (data.result == "1") {
						layer.msg('操作成功!', {
							icon : 1,
							time : 800
						});
						setTimeout(function() {
							$("#table").bootstrapTable('refresh');
						}, 500);
					} else {
						layer.msg('操作失败!', {
							icon : 2,
							time : 800
						});
					}
				},
				error : function() {
					layer.msg('系统繁忙，请稍后再试!', {
						icon : 5,
						time : 800
					});
				}
			});
		});
	}
	
	function fileChange() {
        if (image_check('imgFile')) {
	        $.ajaxFileUpload({
				url: "${pageContext.request.contextPath}/upload_img",
	            type: 'post',
	            secureuri: false,
	            fileElementId: "imgFile",
	            dataType: 'json',
	            async: false,
	            data: {
	                "folderId": nID,
	            },
	            success: function (data) {
	            	console.log(data.url);
	            	imgUrl= data.url;
	            	$('#image').attr('src', '${pageContext.request.contextPath}/' + data.url);
					$("#image").show();
					$("#imgBtn").hide();
	            }
			});
        }
    }

	function releaseNotice(id,state) {
		console.log(state);
		var noticeState;
		if(state==0){
			noticeState="1";
		}else if(state==1){
			noticeState="0";
		}
			$.ajax({
				url : "${pageContext.request.contextPath}/notice/releaseNotice",
				type : "post",
				data : {
					noticeId : id,
					noticeState:noticeState
				},
				dataType : "json",
				success : function(data) {
					if (data.result =="1") {
						layer.msg('操作成功!', {
							icon : 1,
							time : 800
						});
						setTimeout(function() {
							$("#table").bootstrapTable('refresh');
						}, 500);
					} else {
						layer.msg('操作失败!', {
							icon : 2,
							time : 800
						});
					}
				},
				error : function() {
					layer.msg('系统繁忙，请稍后再试!', {
						icon : 5,
						time : 800
					});
				}
			});
	}
	
	 function image_check(feid) { //自己添加的文件后缀名的验证
	        var img = document.getElementById(feid);
	        return /.(jpg|png|gif|bmp)$/.test(img.value)?true:(function() {
	        	layer.alert('图片格式仅支持jpg、png、gif、bmp格式，且区分大小写。');
	            return false;
	        })();
	    }
	
	 function guid() {
	        function S4() {
	           return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
	        }
	        return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
	    }
	 function Querry(){
		 $("#table").bootstrapTable('refresh');
	}
	
</script>
</html>
